<template>
  <view v-if="show" class="cascade_box">
    <view class="cascade_hei" :animation="animationData.fadeAnim"></view>
    <view class="cascade_find" :animation="animationData.showAnim">
      <view class="cascade_header">
        <text class="quxiao" @click="cancelPicker">取消</text>
        <text class="queren" @click="onAddressPick">确认</text>
      </view>
      <view class="show-text">{{selectText}}</view>
      <picker-view :value="defaultValue" indicator-style="height: 80rpx;font-size: 38rpx"
        style="width: 100%; height: 400rpx;" @change="bindChange" immediate-change='true' @pickstart="pickstart" @pickend="pickend" >    <!-- 省 -->
        <picker-view-column class="pvc">
          <block v-for="(item, index) in provinces" :key="index">
            <view style="text-align:center;">{{ item.areaName | filterName }}</view>
          </block>
        </picker-view-column>
        <!--  市 -->
        <picker-view-column class="pvc">
          <block v-for="(item, index) in cities" :key="index">
            <view style="text-align:center;">{{ item.areaName | filterName }}</view>
          </block>
        </picker-view-column>
        <!--  区 -->
        <picker-view-column class="pvc">
          <block v-for="(item, index) in areas" :key="index">
            <view style="text-align:center;">{{ item.areaName | filterName }}</view>
          </block>
        </picker-view-column>
        <!--  街道 -->
        <picker-view-column class="pvc">
          <block v-for="(item, index) in towns" :key="index">
            <view style="text-align:center;">{{ item.areaName | filterName }}</view>
          </block>
        </picker-view-column>
      </picker-view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script>
  import api from '@/api/api';
  export default {
    data() {
      return {
        provinces: [], //获取到的所有的省
        cities: [], //选择的该省的所有市
        areas: [], //选择的该市的所有区县
        towns: [],
        defaultValue: [0, 0, 0, 0],
        selectedRegion: [0, 0, 0, 0],
        animationData: {},
        show: false,
        province_code: '110000000', //默认省份id
        city_code: '110100000', //默认城市id
        province: '',
        city: '',
        provinceCode: '',
        cityCode: '',
        provinceName: '',
        cityName: '',
        town: '',
        townName: '',
        townCode: '',
        noSelect: {
          areaCode: null,
          areaId: null,
          areaName: "暂不选择",
          areaType: "noSelct"
        },
        selectText: '',
        sureSelectRegion: [],
        sureSelectCode: [],
        isMoving:false
      };
    },

    watch: {
      // provinces(val, oldVal) {
      //   if (val !== oldVal) {
      //     this.provinces.push(this.noSelect)
      //   }
      // },
      cities(val, oldVal) {
        if (val !== oldVal) {
          this.cities.push(this.noSelect)
        }
      },
      areas(val, oldVal) {
        if (val !== oldVal) {
          this.areas.push(this.noSelect)
        }
      },
      towns(val, oldVal) {
        if (val !== oldVal) {
          this.towns.push(this.noSelect)
        }
      },
    },
    filters: {
      filterName(name) {
        let value;
        if (name.length > 5) {
          value = name.substring(0, 5) + '...'
        } else {
          value = name
        }
        return value
      }
    },
    mounted() {

    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      pickstart() {
        this.isMoving = true;
      },
      pickend() {
        this.isMoving = false;
      },
      pickerConfirm(e) {
        if (this.isMoving) {
          this.handleShowTextToast('运动中，不能点击哦')
          return;
        }
      },

      setAddressPickerValue(province, city, area, town) {
        this.province = province;
        this.city = city;
        this.area = area;
        this.town = town;
      },
      showPicker() {
        const fadeAnim = uni.createAnimation({
          duration: 500,
          timingFunction: 'ease'
        });
        this.fadeAnim = fadeAnim;
        const showAnim = uni.createAnimation({
          duration: 500,
          timingFunction: 'ease'
        });
        this.showAnim = showAnim;
        fadeAnim
          .backgroundColor('#000')
          .opacity(0.5)
          .step();
        showAnim.bottom(0 + 'rpx').step();
        this.show = true;
        this.animationData = {
          fadeAnim: fadeAnim.export(),
          showAnim: showAnim.export()
        };
      },
      hidePicker() {
        this.fadeAnim
          .backgroundColor('#fff')
          .opacity(0)
          .step();
        this.showAnim.bottom(-600 + 'rpx').step();
        this.show = false;
        this.animationData = {
          fadeAnim: this.fadeAnim.export(),
          showAnim: this.showAnim.export()
        };
      },
      setSelectCode(arr) {
        this.sureSelectCode = arr
      },
      //点击事件，点击弹出选择页
      async openAddressPicker(flag) {
        let that = this;
        if (this.sureSelectCode.length > 0) {
          await this.reloadProivnce()
        } else {
          this.selectedRegion = [0, 0, 0, 0];
          this.defaultValue = [0, 0, 0, 0];
          await this.loadProivnce(true);
        }
        setTimeout(() => {
          this.showPicker();
        }, 300)
      },
      //取消按钮
      cancelPicker() {
        //这里也是动画，然其高度变为0
        this.hidePicker();
      },
      //确认按钮
      onAddressPick(e) {
        if (this.isMoving) {
          setTimeout(()=>{
            this.okHandle()
          },500)
        } else {
          this.okHandle()
        }

      },
      okHandle(){
        let that = this;
        const [provinceIndex, cityIndex, areaIndex, townIndex] = this.selectedRegion;
        const {
          provinces,
          cities,
          areas,
          towns
        } = this;
        this.province = provinces[provinceIndex];
        this.city = cities[cityIndex] || {};
        this.area = areas[areaIndex] || {};
        this.town = towns[townIndex] || {};
        this.sureSelectRegion = this.selectedRegion;
        this.sureSelectCode = []
        let provinceCode, cityCode, areaCode, townCode;
        provinceCode = this.province.areaCode
        cityCode = this.city.areaCode
        areaCode = this.area.areaCode
        townCode = this.town.areaCode
        this.sureSelectCode.push(provinceCode, cityCode, areaCode, townCode)
        this.sureSelectCode = this.sureSelectCode.filter((item) => (item))
        this.hidePicker();
        this.$emit('areaArray', this.province, this.city, this.area, this.town);
      },
      //滚动选择的时候触发事件
      bindChange(e) {
        //这里是获取picker-view内的picker-view-column 当前选择的是第几项
        const _this = this;
        let e_value = e.detail.value;
        let provinceNum = e_value[0];
        let cityNum = e_value[1];
        let areaNum = e_value[2];
        let townNum = e_value[3];
        //省变化，市区分别选中第一个
        if (this.selectedRegion[0] !== e_value[0]) {
          //   if (e_value[0] == _this.provinces.length - 1) {
          //     _this.areas = []
          //     _this.cities = []
          //     _this.towns = []

          //   } else {
          //     _this.loadCity(_this.provinces[e_value[0]].areaCode);
          //   _this.selectText = _this.provinces[e_value[0]].areaName
          //   }
          _this.loadCity(_this.provinces[e_value[0]].areaCode)
          _this.selectText = _this.provinces[e_value[0]].areaName
          _this.selectedRegion = [e_value[0], 0, 0, 0]
          //市变化，区选中第一个
        } else if (this.selectedRegion[1] !== e_value[1]) {
          this.selectedRegion = [e_value[0], e_value[1], 0, 0];
          if (e_value[1] == _this.cities.length - 1) {
            _this.areas = []
            _this.towns = []
            _this.selectText = _this.provinces[e_value[0]].areaName
          } else {
            _this.loadArea(_this.cities[e_value[1]].areaCode);
            _this.selectText = _this.cities[e_value[1]].areaName
          }
        } else if (this.selectedRegion[2] !== e_value[2]) {
          //区变化，省市不变
          this.selectedRegion = [e_value[0], e_value[1], e_value[2], 0];
          if (e_value[2] == _this.areas.length - 1) {
            _this.towns = [];
            _this.selectText = _this.cities[e_value[1]].areaName
          } else {
            _this.loadTown(_this.areas[e_value[2]].areaCode)
            _this.selectText = _this.areas[e_value[2]].areaName
          }
        } else if (this.selectedRegion[3] !== e_value[3]) {
          //街道变化，区不变
          this.selectedRegion = [e_value[0], e_value[1], e_value[2], e_value[3]];
          if (e_value[3] == _this.towns.length - 1) {
            _this.selectText = _this.areas[e_value[2]].areaName
          } else {
            _this.selectText = _this.towns[e_value[3]].areaName
          }
        }
        this.defaultValue = this.selectedRegion;
      },
      // 点击初始化加载省市区列表
      loadProivnce: async function(flag) {
        let that = this;
        // 获取所有省份
        const json = await api.getProvinceList();
        if (json.code === 1000) {
          that.provinces = json.data.content;
          //根据默认省，获取默认市
          const json1 = await api.getCityList(that.province_code);
          if (json1.code === 1000) {
            that.cities = json1.data.content;
            //根据默认市，获取默认区
            // that.loadArea(that.cities[0].areaCode);
            const json2 = await api.getAreaList(that.cities[0].areaCode);
            if (json2.code === 1000) {
              that.areas = json2.data.content;
              // that.loadTown(that.areas[0].areaCode)
              const json3 = await api.getAreasListNew({
                query: {
                  area_no: "1",
                  area_type: 'town',
                  parent_code: that.areas[0].areaCode,
                  sort_type: 'zh'
                }
              });
              if (json3.code === 1000) {
                that.towns = json3.data.content;
                if (flag) {
                  that.selectText = json3.data.content[0].areaName
                }
              }
            }
          }
        }
      },
      // 省市区显数据回显
      reloadProivnce: async function(flag) {
        let that = this;
        // 获取所有省份
        const json = await api.getProvinceList();
        if (json.code === 1000) {
          that.provinces = json.data.content;

          //根据默认省，获取默认市
          const json1 = await api.getCityList(that.sureSelectCode[0]);
          // if (json1.code === 1000) {
          that.cities = json1.data.content;
          //根据默认市，获取默认区
          // that.loadArea(that.cities[0].areaCode);
          const json2 = await api.getAreaList(that.sureSelectCode[1]);
          // if (json2.code === 1000) {
          that.areas = json2.data.content;
          // that.loadTown(that.areas[0].areaCode)
          const json3 = await api.getAreasListNew({
            query: {
              area_no: "1",
              area_type: 'town',
              parent_code: that.sureSelectCode[2],
              sort_type: 'zh'
            }
          });
          // if (json3.code === 1000) {
          that.towns = json3.data.content || [];
          that.sureSelectCode.filter((item) => (item !== null))
          this.sureSelectRegion = this.sureSelectRegion || this.selectedRegion
          let selectIndex = that.sureSelectCode.length - 1
          that.provinces.filter((item, index) => {
            if (item.areaCode == that.sureSelectCode[0]) {
              this.sureSelectRegion[0] = index
            }
          })
          that.cities && that.cities.filter((item, index) => {
            if (item.areaCode == that.sureSelectCode[1]) {
              this.sureSelectRegion[1] = index
            }
          })
          that.areas && that.areas.filter((item, index) => {
            if (item.areaCode == that.sureSelectCode[2]) {
              this.sureSelectRegion[2] = index
            }
          })
          that.towns && that.towns.filter((item, index) => {
            if (item.areaCode == that.sureSelectCode[3]) {
              this.sureSelectRegion[3] = index
            }
          })
          // }
          if (selectIndex == 0) {
            that.selectText = that.provinces[that.sureSelectRegion[selectIndex]].areaName || '北京市'
          } else if (selectIndex == 1) {
            that.selectText = that.cities[that.sureSelectRegion[selectIndex]] ? that.cities[that.sureSelectRegion[
              selectIndex]].areaName : that.provinces[that.sureSelectRegion[0]].areaName
          } else if (selectIndex == 2) {
            that.selectText = that.areas[that.sureSelectRegion[selectIndex]] ? that.areas[that.sureSelectRegion[
              selectIndex]].areaName : that.cities[that.sureSelectRegion[1]].areaName
          } else if (selectIndex == 3) {
            that.selectText = that.towns[that.sureSelectRegion[selectIndex]] ? that.towns[that.sureSelectRegion[
              selectIndex]].areaName : that.areas[that.sureSelectRegion[2]].areaName
          }
          that.selectedRegion = that.sureSelectRegion
          if (that.selectedRegion.length == 3) {
            that.selectedRegion[3] = that.towns.length
          } else if (that.selectedRegion.length == 2) {
            that.selectedRegion[2] = that.areas.length
            that.selectedRegion[3] = that.towns.length
          } else if (that.selectedRegion.length == 1) {
            that.selectedRegion[1] = that.cities.length
            that.selectedRegion[2] = that.areas.length
            that.selectedRegion[3] = that.towns.length
          }
          setTimeout(() => {
            that.defaultValue = that.sureSelectRegion
          }, 200)
          // }
          // }
          // }
        }
      },

      // 加载城市和区域信息
      loadCity: async function(city_code) {
        const that = this;
        const city_json = await api.getCityList(city_code);
        if (city_json.code === 1000) {
          that.cities = city_json.data.content;
          //请求区域信息
          const area_json = await api.getAreaList(city_json.data.content[0].areaCode);
          // console.log(567, street_json)
          if (area_json.code === 1000) {
            that.areas = area_json.data.content;
            that.loadTown(area_json.data.content[0].areaCode)
          } else {
            that.handleShowTextToast(area_json.msg);
          }
        } else {
          that.handleShowTextToast(city_json.msg);
        }
      },
      // 加载区域信息
      loadArea: async function(state_code) {
        const that = this;
        const json = await api.getAreaList(state_code);
        if (json.code === 1000) {
          that.areas = json.data.content;
          that.loadTown(that.areas[0].areaCode)
        } else {
          that.handleShowTextToast(json.msg);
        }
      },
      // 加载街道信息
      loadTown: async function(state_code) {
        const that = this;
        const json = await api.getAreasListNew({
          query: {
            // area_no: "1",
            area_type: 'town',
            parent_code: state_code,
            // sort_type: 'zh'
          }
        });
        if (json.code === 1000) {
          that.towns = json.data.content;
        } else {
          that.handleShowTextToast(json.msg);
        }
      }
    }
  };
</script>
<style lang="less">
  .cascade_box {
    font-size: 32rpx;
    width: 100%;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 99999;
  }

  .cascade_hei {
    width: 100%;
    height: 100vh;
    background: #fff;
    opacity: 0;
  }

  .cascade_find {
    width: 100%;
    height: 680rpx;
    position: fixed;
    bottom: -680rpx;
    left: 0;
    background: #fff;
    z-index: 99999;
  }

  .quxiao,
  .queren {
    display: block;
    position: absolute;
    width: 100rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    color: #0cbb0a;
  }

  .quxiao {
    color: #939393;
  }

  .queren {
    right: 0;
    top: 0;
  }

  .pvc {
    font-size: 38rpx;
  }

  .cascade_header {
    height: 80rpx;
    width: 100%;
    margin-bottom: 20rpx;
  }

  .show-text {
    height: 84rpx;
    background: #F7F5F4;
    font-size: 26rpx;
    color: #1A1A1A;
    display: flex;
    align-items: center;
    padding: 0 64rpx;
  }

  picker-view picker-view-column view {
    line-height: 38px;
  }
</style>
